<template>
  <a-modal :title="calcTitle" :visible="visible" width="1150px" @cancel="visible = false">
    <a-steps :current="current" size="small" v-if="operatorType === 'add' || operatorType === 'edit'">
      <a-step title="基础规则">1</a-step>
      <a-step title="其他规则"/>
      <a-step title="确认创建"/>
    </a-steps>
    <template v-if="current === 0 || current === 2">
      <entity-view ref="firstStepForm" :operatorType="operatorType" :model="beanInfo" form-item-width="100%"
                   :labelCol="{span:4}" :wrapperCol="{span:8}" :rules="firstStepRules">
        <form-item label="收银员返现活动名称" prop="mcName" v-model="beanInfo.mcName" :disabled="disabled"></form-item>
        <form-item label="机构名称" prop="orgInfo">
          <a-tree-select
            treeDataSimpleMode
            v-model="beanInfo.orgInfo"
            style="width: 100%"
            :tree-data="treeData"
            tree-checkable
            placeholder="请选择参与机构"
            :disabled="disabled"
            :showCheckedStrategy="SHOW_PARENT"
            :getPopupContainer="() => $refs.treeContainer"
            @change="setOrgInfo"
          />
          <div ref="treeContainer" style="position: relative;max-height: 300px;">

          </div>
        </form-item>
        <a-form-model-item label="活动时间" prop="mcDateRange" :autoLink="false" ref="mcDateRange" :style="'width: 100%'"
                           class="form-item">
          <a-row>
            <a-col :span="20">
              <a-range-picker v-model="beanInfo.mcDateRange" allow-clear :disabled="disabled"
                              @change="() => {$refs.mcDateRange.onFieldChange()}"></a-range-picker>
            </a-col>
            <a-col :span="4" v-if="current !== 2">
              <a href="javascript:" @click="setLongTime()" v-if="operatorType === 'add' || operatorType === 'edit'"
                 style="margin-left: 10px">长期</a>
            </a-col>
          </a-row>
        </a-form-model-item>

        <a-form-model-item  label="月均存款平均月数" :autoLink="false" prop="depositMonNum" ref="depositMonNum" :style="'width: 100%'"
                           class="form-item">
          <a-select :disabled="disabled" v-model="beanInfo.depositMonNum">
            <a-select-option value="1"> 1</a-select-option>
            <a-select-option value="2"> 2</a-select-option>
            <a-select-option value="3"> 3</a-select-option>
            <a-select-option value="4"> 4</a-select-option>
            <a-select-option value="5"> 5</a-select-option>
            <a-select-option value="6"> 6</a-select-option>
            <a-select-option value="7"> 7</a-select-option>
            <a-select-option value="8"> 8</a-select-option>
            <a-select-option value="9"> 9</a-select-option>
            <a-select-option value="10"> 10</a-select-option>
            <a-select-option value="11"> 11</a-select-option>
            <a-select-option value="12"> 12</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="活动商户" :wrapperCol="{span:18}" prop="merchantInfo" :auto-link="false"
                           style="width: 100%">
          <!-- 由于在不选择商户时，所属机构商户数据量可能过大，会导致前端卡死。所以暂时修改商户信息为必填。此处提示暂时注释 -->
          <!-- <div style="color: red;">当前如果未选择任何商户或商圈，默认所选机构所有有效商户的收银员达标后享受返现优惠活动</div> !-->
          <div class="child-item">
            <merchant-selector
              ref="merchantSelector"
              v-model="beanInfo.merchantInfo"
              :checked-org-info="checkedOrgInfo"
              :disabled="disabled"
              @uploaded="templateUploaded"
              :hasUploaded="beanInfo.hasUploaded"></merchant-selector>
          </div>
          <div class="child-item">
            <a-row>
              <a-col :span="12" v-if="current !== 2">
                <a-form-model-item label="商圈号" :wrapperCol="{span:24}" labelAlign="left" prop="merchantCircleInfo">
                  <a-row type="flex" justify="space-between" align="bottom">
                    <a-col :span="19">
                      <a-textarea placeholder="请输入商圈编号" v-model="beanInfo.merchantCircleRows"></a-textarea>
                    </a-col>
                    <a-col :span="4">
                      <a href="javascript:" @click="getBusinessArea">确定</a>
                    </a-col>
                  </a-row>
                  <div class="tip">
                    请输入商圈编号，一行一个，最多输入10个<br>
                    已录入{{ beanInfo.merchantCircleInfo.length }}个商圈
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="商圈名称" :labelCol="{span:6}" :wrapperCol="{span:24}" labelAlign="left">
                  <a-row type="flex" justify="space-between" v-for="(i,index) in beanInfo.merchantCircleInfo"
                         :key="i.mchntNo">
                    <a-col :span="20">{{ i.mchntName }}({{i.mchntNo}})</a-col>
                    <a-col :span="4" v-if="current !== 2"><a href="javascript:"
                                                             @click="deleteMerchantInfo('merchantCircleInfo', index)">删除</a>
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
        </a-form-model-item>
        <a-form-model-item label="纳入营销的交易" prop="upLineProduce" ref="upLineProduce" :wrapper-col="{span:20}" :autoLink="false"
                           :style="'width: 100%'" class="form-item">
          <div>线上</div>
          <div :style="{ borderBottom: '1px solid #E9E9E9' }">
            <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange"
                        :disabled="disabled">
              全选
            </a-checkbox>
          </div>
          <a-checkbox-group   v-model="beanInfo.upLineProduce" @change="onCheckboxChange" :disabled="disabled">
            <div class="label">刷卡支付：</div>
            <a-space>
              <a-checkbox value="MC001000">POS本行借记卡</a-checkbox>
              <a-checkbox value="MC001001">POS本行贷记卡</a-checkbox>
              <a-checkbox value="MC011000">POS本行贷记卡分期</a-checkbox>
              <a-checkbox value="MC001002">POS他行卡刷卡</a-checkbox>
            </a-space>
            <div class="label">二维码（客户被扫）：</div>
            <a-space>
              <a-checkbox value="MC021000">微信被扫</a-checkbox>
              <a-checkbox value="MC021010">支付宝被扫</a-checkbox>
              <a-checkbox value="MC021020">银联二维码被扫</a-checkbox>
            </a-space>
            <div class="label">二维码（客户主扫）：</div>
            <a-space>
              <a-checkbox value="PM003000">微信扫码支付</a-checkbox>
              <a-checkbox value="PM003010">支付宝扫码支付</a-checkbox>
              <a-checkbox value="PM003020">银联云闪付扫码支付</a-checkbox>
              <a-checkbox value="PM003030">手机银行APP扫码支付</a-checkbox>
            </a-space>
          </a-checkbox-group>
        </a-form-model-item>
        <a-form-model-item label="纳入营销的交易" prop="onLineProduce" ref="onLineProduce" :wrapper-col="{span:20}" :autoLink="false"
                           :style="'width: 100%'" class="form-item">
          <div>线下</div>
          <div :style="{ borderBottom: '1px solid #E9E9E9' }">
            <a-checkbox :indeterminate="indeterminate2" :checked="checkAll2" @change="onLineProduceChange"
                        :disabled="disabled">
              全选
            </a-checkbox>
          </div>
          <a-checkbox-group
                             v-model="beanInfo.onLineProduce"
                             @change="onCheckboxChangeTitleLevel" :disabled="disabled">
            <div class="label">微信APP：</div>
            <a-space>
              <a-checkbox value="PM002000">微信公众号支付</a-checkbox>
              <a-checkbox value="PM002010">微信小程序支付</a-checkbox>
              <a-checkbox value="PM002020">微信APP</a-checkbox>
            </a-space>
            <div class="label">二维码（客户主扫）：</div>
            <a-space>
              <a-checkbox value="PM003000">微信扫码支付</a-checkbox>
              <a-checkbox value="PM003010">支付宝扫码支付</a-checkbox>
              <a-checkbox value="PM003020">银联云闪付扫码支付</a-checkbox>
              <a-checkbox value="PM003030">手机银行APP扫码支付</a-checkbox>
            </a-space>
            <div class="label">本行借记卡快捷：</div>
            <a-space>
              <a-checkbox value="PM001000">新卡支付</a-checkbox>
              <a-checkbox value="PM011000">银行卡首次签约并支付</a-checkbox>
              <a-checkbox value="PM004000">本行卡快捷支付</a-checkbox>
            </a-space>
            <div class="label">本行贷记卡快捷：</div>
            <a-space>
              <a-checkbox value="PM001001">新卡支付</a-checkbox>
              <a-checkbox value="PM011001">银行卡首次签约并支付</a-checkbox>
              <a-checkbox value="PM004001">银联无卡快捷支付</a-checkbox>
            </a-space>

            <div class="label">他行卡快捷：</div>
            <a-space>
              <a-checkbox value="PM001002">新卡支付</a-checkbox>
              <a-checkbox value="PM011002">银行卡首次签约并支付</a-checkbox>
              <a-checkbox value="PM004012">>银联无跳转支付(后台接口)</a-checkbox>
              <a-checkbox value="PM004022">银联无卡快捷支付</a-checkbox>
            </a-space>

            <div class="label">本行手机银行APP：</div>
            <a-space>
              <a-checkbox value="PM005000">手机银行SDK支付</a-checkbox>
              <a-checkbox value="PM009000">手机银行银行卡+积分支付</a-checkbox>
            </a-space>
            <div class="label">银联云闪付三合一：</div>
            <a-space>
              <a-checkbox value="PM006000">银联云闪付支付</a-checkbox>
            </a-space>
            <div class="label">个人网关：</div>
            <a-space>
              <a-checkbox value="PM007000">本行个人网关支付</a-checkbox>
              <a-checkbox value="PM007020">他行个人网关支付</a-checkbox>
            </a-space>
            <div class="label">企业网关：</div>
            <a-space>
              <a-checkbox value="PM007010">本行企业网关支付</a-checkbox>
              <a-checkbox value="PM007030">他行企业网关支付</a-checkbox>
            </a-space>
            <div class="label">本行贷记卡分期：</div>
            <a-space>
              <a-checkbox value="PM010000">银行卡分期支付</a-checkbox>
              <a-checkbox value="PM012000">手机银行扫码分期支付</a-checkbox>
            </a-space>
          </a-checkbox-group>

        </a-form-model-item>
      </entity-view>
    </template>
    <div class="hr" v-if="current === 2"></div>
    <template v-if="current === 1 || current === 2">
      <entity-view ref="secondStepForm" :operatorType="operatorType" :model="beanInfo" :visible="visible"
                   form-item-width="100%" :labelCol="{span:6}" :wrapperCol="{span:10}" :rules="secondStepRules">
        <form-item label="达标条件" :wrapper-col="{span:12}">
          <a-checkbox  :disabled="disabled" v-model="beanInfo.stockMchnt" @change="onStockMchntFlag">存量商户</a-checkbox>
        </form-item>

        <div class="hr" v-if="current === 2"></div>
        <a-form-model-item label=" " prop="ruleInfo" ref="ruleInfo" :auto-link="false"
                           :wrapper-col="{span: 18}" :style="'width: 100%'" class="form-item">
          <a-radio-group  v-model="beanInfo.cashbackMethod" :options="[
            {value: '0', label: '商户上月日均存款'},
            {value: '1', label: '交易笔数'},
             {value: '2', label: '交易金额'},
              {value: '3', label: '手续费金额'},
          ]" :disabled="disabled" @change="onCashbackChange">
          </a-radio-group>

          <div class="child-item" v-if="beanInfo.cashbackMethod === '0'">
            <div class="step-rule-item" v-for="(i, index) in beanInfo.ruleInfo" :key="index">
              <a-input-number :min="0" class="small-input" size="small" :disabled="disabled || index > 0"
                              v-model="i.criteriaFloor"/>
              <span>至</span>
              <a-input-number :min="0" :max-length="9" class="small-input" size="small" :disabled="disabled"
                              v-model="i.criteriaCelling"/>
              <span>元则</span>

              <a-select class="small-select" size="small" :disabled="disabled" v-model="i.discountType">
                <a-select-option value="0">免手续费</a-select-option>
                <a-select-option value="1">费率打折</a-select-option>
                <a-select-option value="2">固定费率</a-select-option>
              </a-select>
              <span v-if="i.discountType === '1'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                           v-model="i.discount"/>折,</span>
              <span v-if="i.discountType === '2'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                           v-model="i.discount"/>%,
              </span>

              <span>优惠上限规则 </span>
              <a-select class="small-select2" size="small" :disabled="disabled" v-model="i.calRuleNo">
                <a-select-option value="0000">无上限</a-select-option>
                <a-select-option value="0001">指定具体数值</a-select-option>
              </a-select>
              <span v-if="i.calRuleNo === '0001'">
                <a-input :disabled="disabled" :max-length="9" class="small-input" size="small" v-model="i.discountLimit"/>元
              </span>
              <a href="javascript:" v-if="current !== 2" @click="deleteCashbackRule(index)">删除</a>
            </div>
            <a href="javascript:" @click="addStepRuleItem"
               v-if="current !== 2 && beanInfo.ruleInfo.length > 0">添加区间策略</a>
          </div>
          <!--end 商户上月日均存款-->


          <!--交易笔数-->
          <div class="child-item" v-if="beanInfo.cashbackMethod === '1'">
            <a-row>
              <a-col :span="5">有效交易为:交易金额≥</a-col>
              <a-col :span="3">
                <a-input :disabled="disabled" :max-length="9" class="small-input" size="small"   v-model="beanInfo.effectiveLimitTranNum"/>
              </a-col>
              <a-col :span="1">元,</a-col>
              <a-col :span="3">有效周期:</a-col>
              <a-col :span="12">
                <a-select class="small-select2" size="small" :disabled="disabled" v-model="beanInfo.discoutPeriodTranNum">
                  <a-select-option value="0">与活动起止一致</a-select-option>
                  <a-select-option value="2">自然月度</a-select-option>
                  <a-select-option value="3">自然季度</a-select-option>
                  <a-select-option value="4">自然年度</a-select-option>
                </a-select>
              </a-col>
            </a-row>
            <div  v-for="(i, index) in beanInfo.ruleInfo" :key="index">
              <a-row>
                <a-col :span="4">周期内有效交易</a-col>
                <a-col :span="3">
                  <a-input-number :min="0" class="small-input" size="small" :disabled="disabled || index > 0"  v-model="i.criteriaFloor"/>
                </a-col>
                <a-col :span="1">至</a-col>
                <a-col :span="3">
                  <a-input-number :min="0" :max-length="9" class="small-input" size="small" :disabled="disabled"
                                  v-model="i.criteriaCelling"/>
                </a-col>
                <a-col :span="1">笔则</a-col>
                <a-col :span="4">
                  <a-select class="small-select" size="small" :disabled="disabled" v-model="i.discountType">
                    <a-select-option value="0">免手续费</a-select-option>
                    <a-select-option value="1">费率打折</a-select-option>
                    <a-select-option value="2">固定费率</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <span v-if="i.discountType === '1'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                                                      v-model="i.discount"/>折,</span>
                  <span v-if="i.discountType === '2'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                               v-model="i.discount"/>%,</span>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="3">优惠上限规则</a-col>
                <a-col :span="5">
                  <a-select class="small-select2" size="small" :disabled="disabled" v-model="i.calRuleNo">
                    <a-select-option value="0000">无上限</a-select-option>
                    <a-select-option value="0001">指定具体数值</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <span v-if="i.calRuleNo === '0001'">
                  <a-input :disabled="disabled" :max-length="9" class="small-input" size="small" v-model="i.discountLimit"/>元
                  </span>
                </a-col>
              </a-row>

              <a href="javascript:" v-if="current !== 2" @click="deleteCashbackRule(index)">删除</a>
            </div>
            <a href="javascript:" @click="addStepRuleItem"
               v-if="current !== 2 && beanInfo.ruleInfo.length > 0">添加区间策略</a>
          </div>
          <!--end交易比数-->

          <!--交易金额-->
          <div class="child-item" v-if="beanInfo.cashbackMethod === '2'">
            <a-row>
              <a-col :span="5">有效交易为:交易金额≥</a-col>
              <a-col :span="3">
                <a-input :disabled="disabled" :max-length="9" class="small-input" size="small"  v-model="beanInfo.effectiveLimitTranMoney"/>
              </a-col>
              <a-col :span="1">元,</a-col>
              <a-col :span="3">有效周期:</a-col>
              <a-col :span="12">
                <a-select class="small-select2" size="small" :disabled="disabled" v-model="beanInfo.discoutPeriodTranMoney">
                  <a-select-option value="0">与活动起止一致</a-select-option>
                  <a-select-option value="2">自然月度</a-select-option>
                  <a-select-option value="3">自然季度</a-select-option>
                  <a-select-option value="4">自然年度</a-select-option>
                </a-select>
              </a-col>
            </a-row>
            <div  v-for="(i, index) in beanInfo.ruleInfo" :key="index">
              <a-row>
                <a-col :span="4">周期内有效交易额</a-col>
                <a-col :span="3">
                  <a-input-number :min="0" class="small-input" size="small" :disabled="disabled || index > 0"  v-model="i.criteriaFloor"/>
                </a-col>
                <a-col :span="1">至</a-col>
                <a-col :span="3">
                  <a-input-number :min="0" :max-length="9" class="small-input" size="small" :disabled="disabled"
                                  v-model="i.criteriaCelling"/>
                </a-col>
                <a-col :span="1">笔则</a-col>
                <a-col :span="4">
                  <a-select class="small-select" size="small" :disabled="disabled" v-model="i.discountType">
                    <a-select-option value="0">免手续费</a-select-option>
                    <a-select-option value="1">费率打折</a-select-option>
                    <a-select-option value="2">固定费率</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <span v-if="i.discountType === '1'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                               v-model="i.discount"/>折,</span>
                  <span v-if="i.discountType === '2'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                               v-model="i.discount"/>%,</span>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="3">优惠上限规则</a-col>
                <a-col :span="5">
                  <a-select class="small-select2" size="small" :disabled="disabled" v-model="i.calRuleNo">
                    <a-select-option value="0000">无上限</a-select-option>
                    <a-select-option value="0001">指定具体数值</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <span v-if="i.calRuleNo === '0001'">
                  <a-input :disabled="disabled" :max-length="9" class="small-input" size="small" v-model="i.discountLimit"/>元
                  </span>
                </a-col>
              </a-row>


              <a href="javascript:" v-if="current !== 2" @click="deleteCashbackRule(index)">删除</a>
            </div>
            <a href="javascript:" @click="addStepRuleItem"
               v-if="current !== 2 && beanInfo.ruleInfo.length > 0">添加区间策略</a>
          </div>
          <!--end交易金额-->

          <!--手续费金额-->
          <div class="child-item" v-if="beanInfo.cashbackMethod === '3'">
            <a-row>
              <a-col :span="3">有效周期：</a-col>
              <a-col :span="12">
                <a-select class="small-select2" size="small" :disabled="disabled" v-model="beanInfo.discoutPeriodTranNum">
                  <a-select-option value="0">与活动起止一致</a-select-option>
                  <a-select-option value="2">自然月度</a-select-option>
                  <a-select-option value="3">自然季度</a-select-option>
                  <a-select-option value="4">自然年度</a-select-option>
                </a-select>
              </a-col>
            </a-row>
            <div  v-for="(i, index) in beanInfo.ruleInfo" :key="index">
              <a-row>
                <a-col :span="2">周期内</a-col>
                <a-col :span="3">
                  <a-input-number :min="0" class="small-input" size="small" :disabled="disabled || index > 0"  v-model="i.criteriaFloor"/>
                </a-col>
                <a-col :span="1">至</a-col>
                <a-col :span="3">
                  <a-input-number :min="0" :max-length="9" class="small-input" size="small" :disabled="disabled"
                                  v-model="i.criteriaCelling"/>
                </a-col>
                <a-col :span="1">元则</a-col>
                <a-col :span="4">
                  <a-select class="small-select" size="small" :disabled="disabled" v-model="i.discountType">
                    <a-select-option value="0">免手续费</a-select-option>
                    <a-select-option value="1">费率打折</a-select-option>
                    <a-select-option value="2">固定费率</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <span v-if="i.discountType === '1'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                               v-model="i.discount"/>折,</span>
                  <span v-if="i.discountType === '2'"><a-input :disabled="disabled" :max-length="9" class="small-input" size="small"
                                                               v-model="i.discount"/>%,</span>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="3">优惠上限规则</a-col>
                <a-col :span="5">
                  <a-select class="small-select2" size="small" :disabled="disabled" v-model="i.calRuleNo">
                    <a-select-option value="0000">无上限</a-select-option>
                    <a-select-option value="0001">指定具体数值</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <span v-if="i.calRuleNo === '0001'">
                  <a-input :disabled="disabled" :max-length="9" class="small-input" size="small" v-model="i.discountLimit"/>元
                  </span>
                </a-col>
              </a-row>
              <a href="javascript:" v-if="current !== 2" @click="deleteCashbackRule(index)">删除</a>
            </div>
            <a href="javascript:" @click="addStepRuleItem"
               v-if="current !== 2 && beanInfo.ruleInfo.length > 0">添加区间策略</a>
          </div>
          <!--end 手续费金额-->
          <p/>
        </a-form-model-item>

        <form-item label=" " prop="newMchntFlagVerify" ref="newMchntFlagVerify"  :wrapper-col="{span:18}">
        <a-checkbox :disabled="disabled" v-model="beanInfo.newMchntFlagsetBeanInfo">活动期间新增商户</a-checkbox>
        <div class="child-item">
          <a-row>
            <a-col :span="5">新增商户免手续费周期</a-col>
            <a-col :span="2">
              <a-input :min="0" :max-length="9" class="small2-input" v-model="beanInfo.newMchntPeriod" size="small" :disabled="disabled || beanInfo.newMchntFlagView===false"/>
            </a-col>
            <a-col :span="7">自然月 每月优惠交易最大金额</a-col>
            <a-col :span="2">
              <a-input :min="0" :max-length="9" class="small2-input" v-model="beanInfo.newMchntAmountLimit" size="small" :disabled="disabled || beanInfo.newMchntFlagView===false"/>
            </a-col>
            <a-col :span="2">元</a-col>
          </a-row>

          <a-row>
            <a-col :span="24">活动期间15号及之前入驻商户纳入当月统计,15号之后入驻不纳入当月统计!</a-col>
          </a-row>

          <a-row>
            <a-col :span="24"> <a-checkbox :disabled="disabled || beanInfo.newMchntFlagView===false" v-model="beanInfo.postponeFlagView">新增商户营销结束日期在营销活动结束日期之后，则后延到新商户的营销周期结束</a-checkbox></a-col>
          </a-row>

          <a-row>
            <a-col :span="24">示例：</a-col>
          </a-row>

          <a-row>
            <a-col :span="12">活动在2020/1/31结束,新增商户在2019/12/28入驻成功</a-col>
            <a-col :span="12">则按照免2个月手续费,且后延到营销周期结束的规律</a-col>
          </a-row>

          <a-row>
            <a-col :span="12">则其应该免2019/12月,2020/1月,2020/2月手续费！</a-col>
            <a-col :span="12">对于该商户其实际的结束日期为2020/2/29</a-col>
          </a-row>
        </div>
        </form-item>

        <!--手续费优惠规则-->
        <form-item label="手续费优惠规则" :wrapper-col="{span:12}">
          <a-row>
            <a-col  :span="24">
              <a-checkbox :disabled="disabled" v-model="beanInfo.beforeFlagView">达标前的交易通过返现营销</a-checkbox>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="24">
          <a-radio-group class="step-rule-item"  v-model="beanInfo.afterFlagView" :options="[
                {value: '0', label: '达标后的交易通过手续费实时优惠营销'},
                {value: '1', label: '达标后的交易通过返现营销'},]" :disabled="disabled"  @change="onafterFlagView">
          </a-radio-group>
            </a-col>
          </a-row>
        </form-item>
        <!--end 手续费优惠规则-->

        <!--预计活动资金：-->
        <form-item prop="budgetVerify" ref="budgetVerify"  label="预计活动资金" :wrapper-col="{span:12}">
          <a-col :span="12">
            <a-input v-model="beanInfo.budget" :disabled="disabled || beanInfo.afterFlagView==='0' && beanInfo.beforeFlagView===false " />
          </a-col>
          <a-col :span="1">元</a-col>
        </form-item>
        <!--end 预计活动资金-->

        <!--单个收银员返现退出条件-->
        <form-item label="单个收银员返现退出条件" prop="statPeriodVerify" ref="statPeriodVerify" :wrapper-col="{span:12}">
          <div style="line-height: 1.4;margin-top: 10px">
            以下为单个收银员退出条件营销活动，<br>
            不配置则活动结束自然退出(可能需要补营销资金)，<br>
            <span style="color: #F1545D;">满足其中之一则收银员不再享受返现优惠！</span>
          </div>
          <div  class="child-item2">
            <a-row>
              <a-col :span="9">统计周期：</a-col>
              <a-col :span="12">
                <a-select size="small" :disabled="disabled" v-model="beanInfo.statPeriod">
                  <a-select-option value="0">请选择</a-select-option>
                  <a-select-option value="1">与活动起止一致</a-select-option>
                  <a-select-option value="2">自然月度</a-select-option>
                  <a-select-option value="3">自然季度</a-select-option>
                  <a-select-option value="4">自然年度</a-select-option>
                </a-select>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="9">单个存量商户优惠交易笔数上限:</a-col>
              <a-col :span="12"><a-input v-model="beanInfo.quantityLimit" :disabled="disabled || beanInfo.statPeriod==='0' " /></a-col>
              <a-col :span="1">笔</a-col>
            </a-row>

            <a-row>
              <a-col :span="9">单个存量商户优惠交易金额上限:</a-col>
              <a-col :span="12"><a-input v-model="beanInfo.amountLimit" :disabled="disabled || beanInfo.statPeriod==='0'" /></a-col>
              <a-col :span="1">元</a-col>
            </a-row>

            <a-row>
              <a-col :span="9">单个存量商户手续费优惠额上限:</a-col>
              <a-col :span="12"><a-input v-model="beanInfo.feeLimit" :disabled="disabled || beanInfo.statPeriod==='0'" /></a-col>
              <a-col :span="1">元</a-col>
            </a-row>

            <a-row>
              <span style="color: #F1545D;">以上三个退出条件只能选择一种</span>
            </a-row>
          </div>
        </form-item>
        <!--end 单个收银员返现退出条件-->

<!--        <form-item label="付款账户" prop="payAcctNo" v-model="beanInfo.payAcctNo" input-type="select"-->
<!--                   v-if="operatorType === 'release' &&  beanInfo.skipPub !== '1' || (beanInfo.payAcctNo && current === 2)"-->
<!--                   :options="paymentAccounts"></form-item>-->
        <form-item label="审核意见" prop="auditRefuseReason" v-model="beanInfo.auditRefuseReason" input-type="textarea"
                   v-if="operatorType === 'examine' || (beanInfo.auditRefuseReason && current === 2)"
                   :disabled="operatorType !== 'examine'"></form-item>
        <form-item label="发布意见" prop="publishRefuseReason" v-model="beanInfo.publishRefuseReason" input-type="textarea"
                   v-if="operatorType === 'release' || (beanInfo.publishRefuseReason && current === 2)"
                   :disabled="operatorType !== 'release'"></form-item>
      </entity-view>
    </template>
    <template v-slot:footer>
      <a-space>
        <a-button type="primary" v-if="current < 2" @click="next">下一步</a-button>
        <a-button type="primary" v-if="current === 2 && (operatorType === 'add' || operatorType === 'edit')"
                  @click="submit">确认创建
        </a-button>
        <a-button type="primary" v-if="current === 2 && (operatorType === 'add' || operatorType === 'edit')"
                  @click="save(false)">保存草稿
        </a-button>
          <a-button type="primary" v-if="current === 2 && operatorType === 'examine'" @click="examine(true)">审核通过
        </a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'examine'" @click="examine(false)">审核退回
        </a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'release' && beanInfo.skipPub !== '1'"
                  @click="release(true)">打款，发布
        </a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'release' && beanInfo.skipPub === '1'"
                  @click="release(true)">发布
        </a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'release'" @click="release(false)">退回修改
        </a-button>
        <a-button type="primary" v-if="current > 0 && (operatorType === 'add' || operatorType === 'edit')"
                  @click="back">返回
        </a-button>
        <a-button type="primary" @click="visible = false">关闭</a-button>
      </a-space>
    </template>
    <merchant-list ref="merchantListModal" @change="merchantListChange"></merchant-list>
  </a-modal>
</template>

<script>
    import FormItem from "../../../../components/common/entityView/FormItem";
    import EntityView from "../../../../components/common/entityView/EntityView";
    import MerchantList from '@/views/bizimpl/upmp/market/cashierManager/MerchantList'
    import MerchantSelector from '@/views/bizimpl/upmp/market/cashierManager/MerchantSelector'
    import {TreeSelect} from 'ant-design-vue';

    const SHOW_PARENT = TreeSelect.SHOW_PARENT;
    import moment from 'moment'

    let loadingLock = false
    let pIdCache = []

    const getChildNodes = (nodes, treeObj) => {
        let childNodes = []
        nodes.forEach(node => {
            if (typeof node === 'string') {
                node = treeObj[node]
            }
            if (node && !pIdCache.includes(node.pId)) {
                const filterNodes = Object.values(treeObj).filter(i => i.pId === node.id)
                if (filterNodes.length) {
                    childNodes.push(...filterNodes)
                    pIdCache.push(node.id)
                    childNodes.push(...getChildNodes(filterNodes, treeObj))
                }
            }
        })
        return childNodes
    }
    const getParentNodes = (nodes, treeObj) => {
        let parentNodes = []
        nodes.forEach(node => {
            if (typeof node === 'string') {
                node = treeObj[node]
            }
            if (node && node.pId && node.pId !== '999999999' && pIdCache.includes(node.pId) === false) {
                pIdCache.push(node.pId)
                const filterNodes = Object.values(treeObj).filter(i => i.id === node.pId)
                if (filterNodes.length) {
                    parentNodes.push(...filterNodes)
                    parentNodes.push(...getParentNodes(parentNodes, treeObj))
                }
            }
        })
        return parentNodes
    }

    const beanInfoInitData = {
        mcNo: "", // 营销活动编号
        mcName: "", // 营销活动名称
        orgInfo: [], // 参与机构
        checkedOrgInfo: [], // 已选中的参与机构
        mcDateRange: [], // 活动起始时间
        merchantInfo: [], // 商户信息
        merchantCircleInfo: [], // 商圈信息
        upLineProduce: [], // 纳入营销的交易
        cashbackMethod: "0", // 营销方式交易类型
        budget: null, // 返现金额  数字格式 隐式转换
        ruleInfo: [{
            discountType: "0", // 优惠类型
            calRuleNo:'0000',//优惠上限规则
        }], // 营销方式阶梯规则
        hasUploaded: false,
        mrctFilePath: '',
        //优惠劵---------------
        ruleInfoList: [{}],
        newMchntFlagView:false,//活动期间新增商户
        beforeFlagView:false,//达标前的交易通过返现营销
        stockMchnt:true,//达标条件
        postponeFlagView:false,//新增商户营销结束日期在营销活动结束日期之后
        depositMonNum:"1",//月均存款平均月数
        afterFlagView:'0',//手续费优惠规则
        statPeriod:'0',//统计周期
        onLineProduce:[],//纳入营销的交易线下
        effectiveLimitTranNum:null,// 有效交易为：交易金额 ≥ 交易笔数
        effectiveLimitTranMoney:null,//有效交易为：交易金额 ≥交易笔数
        //有效周期
        discoutPeriodTranNum:'0',
        discoutPeriodTranMoney:'0',
        discoutPeriodFeeMoney:'0',
        //end有效周期
        newMchntPeriod:null,//新增商户免手续费周期
        newMchntAmountLimit:null,//每月优惠交易最大金额
        quantityLimit:null,//单个存量商户优惠交易笔数上限
        amountLimit:null,//单个存量商户优惠交易金额上限
        feeLimit:null,//单个存量商户手续费优惠额上限
    }

    export default {
        name: "CommissionMarketManagerOperation",
        components: {EntityView, FormItem, MerchantList, MerchantSelector},
        data() {
            const mcDataRangeValidator = (rule, val, cb) => {
                if (!val || val.length === 0) {
                    cb(new Error('请选择时间范围'));
                } else {
                    cb();
                }
            }
            const ruleInfoValidator = (rule, val, cb) => {
                for (let i = 0; i < val.length; i++) {
                    const item = val[i];
                    console.log(item)
                    if (this.beanInfo.cashbackMethod === '0') {
                        if (!(
                            item.criteriaFloor !== undefined && item.criteriaFloor !== null &&
                            item.criteriaCelling !== undefined && item.criteriaCelling !== null &&
                            item.discountType !== undefined && item.discountType !== null
                            // item.discount !== undefined && item.discount !== null
                        )) {
                            cb(new Error(`请完善第${i + 1}行区间策略`));
                            return
                        }
                    } else if (this.beanInfo.cashbackMethod === '1' || this.beanInfo.cashbackMethod === '2' || this.beanInfo.cashbackMethod === '3') {
                        if (!(
                            item.criteriaFloor !== undefined && item.criteriaFloor !== null &&
                            item.criteriaCelling !== undefined && item.criteriaCelling !== null &&
                            item.discountType !== undefined && item.discountType !== null
                            // item.discount !== undefined && item.discount !== null
                        )) {
                            cb(new Error(`请完善第${i + 1}行区间策略`));
                            return
                        }
                    }
                    if (Number(item.criteriaFloor) > Number(item.criteriaCelling)) {
                        cb(new Error(`第${i + 1}行区间策略的交易金额区间的结束值必须大于区间的开始值`));
                        return
                    }
                    // if (item.cashbackRatio <= 0) {
                    //   cb(new Error(`第${i + 1}行营销方式阶梯的返现比例数值不能为零并且不能大于1000`));
                    //   return
                    // }
                    if (item.discountType==='1' && (!item.discount || !item.discount.length)){
                        cb(new Error('区间策略费率打折请输入折扣'));
                        return
                    }
                    if (item.discountType==='2' && (!item.discount || !item.discount.length)){
                        cb(new Error('区间策略固定费率请输入费率'));
                        return
                    }
                    if (item.calRuleNo ==='1' && (!item.discountLimit || !item.discountLimit.length)){
                        cb(new Error('区间策略指定具体数值请输入金额'));
                        return
                    }

                }
                if (this.beanInfo.cashbackMethod ==='1'  && !this.beanInfo.effectiveLimitTranNum.length){
                    cb(new Error('交易金额不能为空'));
                }
                if ( this.beanInfo.cashbackMethod ==='2' && !this.beanInfo.effectiveLimitTranMoney.length){
                    cb(new Error('交易金额不能为空'));
                }
                if (this.beanInfo.cashbackMethod ==='3' && this.beanInfo.discoutPeriodTranNum == '0'){
                    cb(new Error('有效周期不能为空'));
                }
                cb();
            }
            const payAcctNoValidator = (rule, val, cb) => {
                if (this.operatorType === 'release') {
                    if (!this.beanInfo.payAcctNo && this.beanInfo.skipPub !== '1') {
                        cb(new Error(`请选择支付账号`));
                    } else {
                        cb();
                    }
                } else {
                    cb()
                }
            }
            const merchantInfoValidator = (rule, val, cb) => {
                if (!this.beanInfo.merchantInfo.length && !this.beanInfo.merchantCircleInfo.length && !this.beanInfo.hasUploaded) {
                    cb(new Error(`请输入商户或商圈信息，或者使用导入功能`));
                } else {
                    cb()
                }
            }
            const produceValidator = (rule, val, cb) => {
                if (!this.beanInfo.upLineProduce.length && !this.beanInfo.onLineProduce.length) {
                    cb(new Error(`请勾选需要纳入营销的交易方式，线上或线下必须选择一个。`));
                } else {
                    cb()
                }
            }
            const budgetValidator = (rule, val, cb) => {
                if(this.beanInfo.afterFlagView ==='0'){
                    cb()
                }else {
                    if (this.beanInfo.budget.length || this.beanInfo.budget){
                        cb()
                    } else {
                        cb(new Error(`预计活动资金不能为空`));
                    }
                }
            }

            const newMchntFlagValidator = (rule, val, cb) => {
                if(this.beanInfo.newMchntFlagView ===false){
                    cb()
                }else {
                    if (!this.beanInfo.newMchntPeriod.length){
                        cb(new Error(`新增商户免手续费周期不能为空`));
                    } else {
                        cb()
                    }
                }
            }
            const statPeriodValidator = (rule, val, cb) => {
                // 预计活动资金不能为空
                if(this.beanInfo.statPeriod ==='0'){
                    cb()
                }else {
                    // (!item.discountLimit || !item.discountLimit.length)
                    if (
                        ((this.beanInfo.quantityLimit || this.beanInfo.quantityLimit.length) && (!this.beanInfo.amountLimit||!this.beanInfo.amountLimit.length) && (!this.beanInfo.feeLimit||!this.beanInfo.feeLimit.length)) ||
                        ((!this.beanInfo.quantityLimit||!this.beanInfo.quantityLimit.length) && (this.beanInfo.amountLimit||this.beanInfo.amountLimit.length) && (!this.beanInfo.feeLimit||!this.beanInfo.feeLimit.length)) ||
                        ((!this.beanInfo.quantityLimit||!this.beanInfo.quantityLimit.length) && (!this.beanInfo.amountLimit||!this.beanInfo.amountLimit.length) && (this.beanInfo.feeLimit||this.beanInfo.feeLimit.length))
                    ) {
                        cb();
                    } else {
                        cb(new Error(`请填写一个单个存量商户优惠退出条件`));
                    }
                }
            }
            return {
                SHOW_PARENT,
                firstStepRules: {
                    mcName: [{required: true, message: "请输入手续费优惠活动名称", trigger: "blur"}],
                    orgInfo: [{required: true, trigger: "change", message: "请选择参与机构"}],
                    mcDateRange: [{required: true, trigger: "change", validator: mcDataRangeValidator,}],
                    depositMonNum: [
                        {required: true, message: "请输入月份", trigger: "blur"},
                    ],
                    upLineProduce: [{required: true, message: "请勾选需要纳入营销的交易方式", trigger: "change", validator: produceValidator}],
                    merchantInfo: [{required: true, trigger: "change", validator: merchantInfoValidator}],
                },
                secondStepRules: {
                    statPeriod: [{required: true, message: "请选择统计周期", trigger: "change"}],
                    ruleInfo: [{required: true, trigger: "blur", validator: ruleInfoValidator,}],
                    payAcctNo: [{required: true, trigger: "blur", validator: payAcctNoValidator,}],
                    statPeriodVerify: [{required: true, trigger: "blur", validator: statPeriodValidator,}],//单个存量商户优惠退出条件校验
                    budgetVerify: [{required: true, trigger: "blur", validator: budgetValidator,}],//
                    newMchntFlagVerify:[{required: true, trigger: "blur", validator: newMchntFlagValidator,}],//
                },
                operatorType: 'add',
                beanInfo: Object.assign({}, beanInfoInitData),
                visible: false,
                current: 0, // 当前步骤
                indeterminate: false,
                checkAll: false,
                indeterminate2: false,
                checkAll2: false,
                treeData: [],
                upLineProduceList: [
                    //刷卡支付
                    'MC001000',
                    'MC001001',
                    'MC011000',
                    'MC001002',
                    //二维码（客户被扫）
                    'MC021000',
                    'MC021010',
                    'MC021020',
                    //二维码（客户主扫)
                    'PM003000',
                    'PM003010',
                    'PM003020',
                    'PM003030',
                ],
                onLineProduceList: [
                    //微信APP
                    'PM002000',
                    'PM002010',
                    'PM002020',
                    //二维码（客户主扫）
                    'PM003000',
                    'PM003010',
                    'PM003020',
                    'PM003030',
                    //本行借记卡快捷
                    'PM001000',
                    'PM011000',
                    'PM004000',
                    //本行贷记卡快捷
                    'PM001001',
                    'PM011001',
                    'PM004001',
                    //他行卡快捷
                    'PM001002',
                    'PM011002',
                    'PM004012',
                    'PM004022',
                    //本行手机银行APP
                    'PM005000',
                    'PM009000',
                    //银联云闪付三合一
                    'PM006000',
                    //个人网关
                    'PM007000',
                    'PM007020',
                    //企业网关
                    'PM007010',
                    'PM007030',
                    //本行贷记卡分期
                    'PM010000',
                    'PM012000',
                ],
                paymentAccounts: [], // 支付账户列表
                checkedOrgInfo: [],

            }
        },
        computed: {
            calcTitle() {
                let title = '商户手续费营销活动';
                switch (this.operatorType) {
                    case 'edit':
                        title = '编辑' + title;
                        break;
                    case 'view':
                        title = '查看' + title;
                        break;
                    case 'add':
                        title = '新增' + title;
                        break;
                    case 'examine':
                        title = '审核' + title;
                        break;
                    case 'release':
                        title = '发布' + title;
                        break;
                }
                return title
            },
            treeObj() {
                return this.treeData.reduce((i, next) => {
                    i[next.id] = next
                    return i
                }, {})
            },
            disabled() {
                return this.current === 2
            },
        },
        methods: {
            async initTreeData() {
                try {
                    const res = await this.$get('/admin/market/cashierManager/getOrgList');
                    this.treeData = (res.data || []).map(i => {
                        i.id = i.orgCode
                        i.orgId = i.orgCode
                        i.value = i.orgCode
                        i.label = i.orgName
                        i.pId = i.superOrgCode
                        return i
                    });
                    if (this.operatorType === 'edit' && this.visible) {
                        this.setOrgInfo()
                    }
                } catch (e) {
                    this.$message.error('获取机构树失败');
                }
            },
            setBeanInfo(beanInfo) {
                let $this = this
                let onLineProduceTempList=[];
                if(beanInfo.onLineProduce.length){
                    beanInfo.onLineProduce.forEach(i => {
                        if (i !== null && i !== undefined) {
                            const index = $this.onLineProduceList.indexOf(i)
                            if (index > -1) {
                                onLineProduceTempList.push(i)
                            }
                        }
                    })
                }
                beanInfo.onLineProduce = onLineProduceTempList;
                let upLineProduceTempList=[];
                if(beanInfo.upLineProduce.length){
                    beanInfo.upLineProduce.forEach(i => {
                        if (i !== null && i !== undefined) {
                            const index = $this.upLineProduceList.indexOf(i)
                            if (index > -1) {
                                upLineProduceTempList.push(i)
                            }
                        }
                    })
                }
                beanInfo.upLineProduce = upLineProduceTempList;

                //
                this.checkAll = beanInfo.upLineProduce.length === this.upLineProduceList.length
                this.checkAll2 = beanInfo.onLineProduce.length === this.onLineProduceList.length
                if (beanInfo.orgInfo.length) {
                    const orgInfo = beanInfo.orgInfo.map(i => {
                        return this.treeObj[i]
                    })
                    orgInfo.forEach(i => {
                        if (i !== null && i !== undefined) {
                            const index = beanInfo.orgInfo.indexOf(i.superOrgCode)
                            if (index > -1) {
                                beanInfo.orgInfo.splice(index, 1)
                            }
                        }
                    })
                }

            },
            show(beanInfo, operatorType) {
                this.operatorType = operatorType;
                this.visible = true;
                switch (operatorType) {
                    case 'add':
                        this.current = 0
                        this.$nextTick(() => {
                            this.$refs.firstStepForm.resetFields()
                            this.checkAll = true
                            this.checkAll2 = true
                            this.beanInfo = Object.assign({}, beanInfoInitData)
                            this.beanInfo.upLineProduce = this.upLineProduceList
                            this.beanInfo.onLineProduce = this.onLineProduceList
                        })
                        break;
                    case 'edit':
                        this.current = 0
                        this.$nextTick(() => {
                            this.$refs.firstStepForm.resetFields()
                            this.setBeanInfo(beanInfo)
                            this.beanInfo = Object.assign({}, beanInfo)
                            this.setOrgInfo()
                        })
                        break;
                    case 'view':
                    case 'examine':
                        this.current = 2
                        this.setBeanInfo(beanInfo)
                        this.beanInfo = beanInfo
                        break
                    case 'release':
                        this.current = 2
                        this.setBeanInfo(beanInfo)
                        this.beanInfo = beanInfo
                        break
                    default:
                        this.$message.error('操作类型错误');
                }
            },
            hide() {
                this.visible = false;
                this.beanInfo = {};
            },
            setLongTime() {
                this.$set(this.beanInfo, 'mcDateRange', [moment().format('YYYY-MM-DD'), moment(new Date('2099/12/31')).format('YYYY-MM-DD')])
            },
            async getBusinessArea() {
                if (this.beanInfo.orgInfo.length === 0) {
                    this.$message.error('请先选择参与机构');
                    return
                }
                if (!this.beanInfo.merchantCircleRows || !this.beanInfo.merchantCircleRows.trim()) {
                    this.$message.error('请输入商圈！');
                    return
                }
                let merchantCircleList = this.beanInfo.merchantCircleRows.split('\n').filter(i => i.trim())
                if (merchantCircleList.length > 10) {
                    this.$message.error('最多输入10个商户号！');
                    return
                }
                // 去重
                merchantCircleList = [...new Set(merchantCircleList)]
                // 与之前输入的商户号对比去重
                let oldMerchantCircleList = this.beanInfo.merchantCircleInfo.map(i => i.mchntNo)
                merchantCircleList = merchantCircleList.filter(i => !oldMerchantCircleList.includes(i))
                if (merchantCircleList.length === 0) {
                    this.$set(this.beanInfo, 'merchantCircleRows', '')
                    this.$message.error('请输入新的商圈！');
                    return
                }
                const hide = this.$message.loading('正在查询商圈信息...', 0);
                try {
                    const res = await this.$postJson('/admin/market/cashierManager/getMcCircletList', {
                        data: merchantCircleList.join(','),
                        selectedOrgInfoList: this.checkedOrgInfo
                    })
                    if (res.data.code === '100000') {
                        let successData = res.data.data.successData
                        // 特殊费率的商户也可以添加
                        const feeMchntObj = res.data.data.feeMchntData;
                        successData = successData.concat(feeMchntObj);

                        const errorData = res.data.data.errorData
                        if (errorData.length > 0) {
                            this.$notification.error({
                                message: '提示',
                                description: `录入的商圈/商户编号：${errorData.map(i => i.mchntNo).join(',')}存在错误，请重新输入！`,
                                duration: 0
                            });
                        }
                        const orgMchntData = res.data.data.orgMchntData;
                        if (orgMchntData.length > 0) {
                            this.$notification.error({
                                message: '提示',
                                description: `输入的商户或商圈内的商户所属的机构与已选的机构不符,${orgMchntData.map(i => i.mchntNo).join(',')}不符合要求，请重新输入！`,
                                duration: 0
                            });
                        }
                        if (successData.length) {
                            this.$set(this.beanInfo, 'merchantCircleInfo', this.beanInfo.merchantCircleInfo.concat(successData))
                        }
                        this.$set(this.beanInfo, 'merchantCircleRows', '')
                    } else {
                        this.$message.error(res.data.message);
                    }
                } catch (e) {
                    this.$message.error('获取商户失败');
                    console.error(e)
                }
                hide()
            },
            //线下
            onCheckAllChange(e) {
                Object.assign(this, {
                    indeterminate: false,
                    checkAll: e.target.checked,
                });
                this.$set(this.beanInfo, 'upLineProduce', e.target.checked ? this.upLineProduceList : []);
                this.$refs.upLineProduce.onFieldChange()
            },
            onCheckboxChange() {
                this.indeterminate = !!this.beanInfo.upLineProduce.length && this.beanInfo.upLineProduce.length < this.upLineProduceList.length;
                this.checkAll = this.beanInfo.upLineProduce.length === this.upLineProduceList.length;
                this.$refs.upLineProduce.onFieldChange()
            },
            //end 线下
            //线上
            onLineProduceChange(e) {
                Object.assign(this, {
                    indeterminate2: false,
                    checkAll2: e.target.checked,
                });
                this.$set(this.beanInfo, 'onLineProduce', e.target.checked ? this.onLineProduceList : []);
                this.$refs.onLineProduce.onFieldChange()
            },
            onCheckboxChangeTitleLevel() {
                this.indeterminate2 = !!this.beanInfo.onLineProduce.length && this.beanInfo.onLineProduce.length < this.onLineProduceList.length;
                this.checkAll2 = this.beanInfo.onLineProduce.length === this.onLineProduceList.length;
                this.$refs.onLineProduce.onFieldChange()
            },
            //end 线下
            async next() {
                if (this.current === 0) {
                    try {
                        await this.$refs.firstStepForm.validate();
                        this.current++
                    } catch (e) {
                        console.log(e);
                    }
                } else if (this.current === 1) {
                    try {
                        await this.$refs.secondStepForm.validate();
                        this.current++
                        if (this.operatorType === 'add') {
                            this.$nextTick(() => {
                                this.$refs.secondStepForm.resetFields()
                            })
                        }
                    } catch (e) {
                        console.log(e);
                    }
                }
            },
            async examine(isExamine) {
                if (loadingLock) {
                    this.$message.error('保存中，请勿重复点击');
                    return
                }
                if (!isExamine && !this.beanInfo.auditRefuseReason) {
                    this.$message.error('请填写审核不通过原因');
                    return
                }
                loadingLock = true
                let hideLoading
                try {
                    await this.$refs.secondStepForm.validate();
                    !this.beanInfo.auditRefuseReason && (this.beanInfo.auditRefuseReason = '')
                    const params = {
                        mcNo: this.beanInfo.mcNo,
                        oprContent: this.beanInfo.auditRefuseReason.trim(),
                        oprType: isExamine ? '1' : '2',
                        mcType:this.beanInfo.mcType
                    }
                    hideLoading = this.$message.loading('提交中...', 0)
                    const res = await this.$postJson(`/admin/market/check/checkSubmit?mcNo=${params.mcNo}&oprContent=${params.oprContent}&oprType=${params.oprType}&mcType=${params.mcType}`)
                    if (res.data.code === '100000') {
                        this.$message.success(`${isExamine ? '审核' : '退回'}成功`)
                        this.visible = false
                        this.$emit('refresh')
                    } else {
                        this.$message.error(res.data.message);
                    }
                } catch (e) {
                    console.log(e)
                    if (e !== false) {
                        this.$message.error('审核出错');
                    }
                }
                hideLoading && hideLoading()
                loadingLock = false
            },
            async release(isRelease) {
                debugger
                if (loadingLock) {
                    this.$message.error('保存中，请勿重复点击');
                    return
                }
                if (!isRelease && !this.beanInfo.publishRefuseReason) {
                    this.$message.error('请填写发布拒绝原因');
                    return
                }
                !this.beanInfo.publishRefuseReason && (this.beanInfo.publishRefuseReason = '')

                let hideLoading
                const params = {
                    mcNo: this.beanInfo.mcNo,
                    oprType: isRelease ? '0' : '1',
                    payAcctNo: this.beanInfo.payAcctNo,
                    oprContent: this.beanInfo.publishRefuseReason.trim(),
                    budget:this.beanInfo.budget
                }
                loadingLock = true
                // todo 判断 skipPub 是否为 1 如果为 1 则不需要验证打款账户信息

                try {
                    await this.$refs.secondStepForm.validate()
                    hideLoading = this.$message.loading('提交中...', 0)
                    const res = await this.$postJson(`/admin/market/commissionRelease/release?mcNo=${params.mcNo}&oprType=${params.oprType}&payAcctNo=${params.payAcctNo}&oprContent=${params.oprContent}&idType=${params.idType}&idNo=${params.idNo}&cellPhoneNumber=${params.cellPhoneNumber}&picCapcha=${params.picCapcha}&smsCapcha=${params.smsCapcha}&budget=${params.budget}`)
                    if (res.data.code === '100000') {
                        this.$message.success('发布成功')
                        this.visible = false
                        this.$emit('refresh')
                    } else {
                        this.$message.error(res.data.message);
                    }
                    hideLoading()
                } catch (e) {
                    console.error(e)
                }
                hideLoading && hideLoading()
                loadingLock = false
            },
            submit() {
                this.save(true)
            },
            async save(isSubmit) {
                if (loadingLock) {
                    this.$message.error('保存中，请勿重复点击');
                    return
                }
                loadingLock = true
                const params = JSON.parse(JSON.stringify(this.beanInfo))
                params.merchantInfo = []
                if (params.mcDateRange.length === 2) {
                    params.mcStartDate = params.mcDateRange[0].substring(0, 10)
                    params.mcEndDate = params.mcDateRange[1].substring(0, 10)
                }
                if (params.ruleInfo) {
                    params.ruleInfo.forEach((i, index) => {
                        i.ruleIndex = index + 1
                    })
                }
                if (params.orgInfo) {
                    params.orgInfo = this.checkedOrgInfo
                    // params.orgInfo = JSON.stringify(params.orgInfo)
                }
                const hide = this.$message.loading("保存中...", 0);
                if (this.operatorType === 'edit') { // 如果是编辑状态则把标记删除的商户或商圈删除
                    const res = await this.getDeleteMerchants()
                    if (!res) {
                        loadingLock = false
                        hide()
                        this.$message.error("保存失败")
                        return
                    } else {
                        params.merchantInfo.push(...res)
                    }
                }
                if (this.beanInfo.merchantInfo && this.beanInfo.merchantInfo.length) {
                    params.merchantInfo.push(...this.beanInfo.merchantInfo.map(i => {
                        i.oprType = i.oprType || 'I'
                        i.mchntType = '0'
                        return i
                    }))
                }

                if (params.merchantCircleInfo) {
                    params.merchantCircleInfo = this.beanInfo.merchantCircleInfo.map(i => {
                        i.oprType = i.oprType || 'I'
                        i.mchntType = '1'
                        return i
                    })
                }
                //优惠劵------------------------
                //达标前的交易通过返现营销
                params.afterFlag=params.afterFlagView

                if(params.beforeFlagView === true){
                    params.beforeFlag='1'
                }else{
                    params.beforeFlag='0'
                }
                //存量商户达标条件
                if (params.stockMchnt===true){
                    params.stockMchntFlag='1'
                }else{
                    params.stockMchntFlag='0'
                }
                //新增商户支持标志
                if(params.newMchntFlagView===true){
                    params.newMchntFlag="1"
                }else{
                    params.newMchntFlag="0"
                }
                //新增商户周期顺延标志
                if (params.postponeFlagView===true){
                    params.postponeFlag='1'
                }else{
                    params.postponeFlag='0'
                }
                params.effectiveLimit=params.effectiveLimitTranNum//有效交易为：交易金额 ≥
                params.ruleInfo.discountPeriod=params.discoutPeriodTranNum//有效周期
                params.stockMchntType=params.cashbackMethod/// 营销方式交易类型
                params.ruleInfoList=params.ruleInfo
                params.orgInfoList=params.orgInfo//机构
                params.merchantList=params.merchantInfo // 商户
                params.circleList=params.merchantCircleInfo  // 商圈
                params.supportType=['1','2','3','4','5','6']
                //未有参数  params.supportTypeStr
                try {
                    if (isSubmit) {
                        params.auditStatus = '01'
                        params.oprType = '1'
                        params.mcStatus='0'
                    }else{
                        params.oprType = '0'
                        params.mcStatus='0'
                        params.auditStatus='00'
                    }
                    const url = isSubmit ? '/admin/market/commissionManager/add' : '/admin/market/commissionManager/add'
                    const res = await this.$postJson(url, params)
                    if (res.data.code === '100000') {
                        this.$message.success('保存成功');
                        this.$emit('refresh')
                        if (isSubmit) {
                            this.visible = false
                        }
                    } else {
                        this.$message.error("保存失败");
                    }
                } catch (e) {
                    console.error(e)
                }
                hide();
                loadingLock = false
            },
            back() {
                this.current--
            },
            addStepRuleItem() {
                console.log("添加区间策略");
                const ruleInfo = this.beanInfo.ruleInfo;
                const lastRule = ruleInfo[ruleInfo.length - 1];
                this.$refs.secondStepForm.validateField('ruleInfo', (errorMessage) => {
                    if (!errorMessage) {
                        ruleInfo.push({
                            criteriaFloor: lastRule.criteriaCelling,//第一个框
                            criteriaCelling: null,//第二个框
                            discountType:'0',//框费率打折或固定费率
                            discount: null,//折或者%
                            calRuleNo:'0000',//优惠上限规则的值
                            discountLimit:null,//指定具体数值后面那个输入框
                        })
                        this.$set(this.beanInfo, 'ruleInfo', ruleInfo);
                    }
                })
            },
            deleteMerchantInfo(key, index) {
                this.$confirm({
                    title: '提示',
                    content: '确定删除该商户？',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        this.beanInfo[key].splice(index, 1)
                        this.$set(this.beanInfo, key, this.beanInfo[key])
                    }
                })
            },
            onCashbackChange() {
                this.beanInfo.stockMchnt=true;
                this.$set(this.beanInfo, 'ruleInfo', [{
                    discountType: '0',
                    //新
                    calRuleNo:'0000',
                    discoutPeriodTranNum:'0',//有效周期
                    discoutPeriodTranMoney:'0',
                    discoutPeriodFeeMoney:'0',
                }])
            },
            onStockMchntFlag() {//存量商户
                console.log("存量商户")
                this.$set(this.beanInfo, 'cashbackMethod', '')
            },
            onafterFlagView(){
                if (this.beanInfo.afterFlagView==='0'){
                    this.beanInfo.budget=null
                }
            },
            deleteCashbackRule(index) {
                const ruleInfo = this.beanInfo.ruleInfo
                ruleInfo.splice(index, 1)
                this.$set(this.beanInfo, 'ruleInfo', ruleInfo)
            },

            setOrgInfo() {
                if (Object.keys(this.treeObj).length) {
                    // get child node
                    let checkedNodes = this.beanInfo.orgInfo.map(i => this.treeObj[i]).filter(i => !!i)
                    pIdCache = []
                    checkedNodes = checkedNodes.concat(getChildNodes(this.beanInfo.orgInfo, this.treeObj))
                    pIdCache = []
                    checkedNodes = checkedNodes.concat(getParentNodes(this.beanInfo.orgInfo, this.treeObj))
                    checkedNodes = Object.values(checkedNodes.reduce((item, next) => {
                        item[next.id] = next
                        return item
                    }, {}))
                    this.checkedOrgInfo = checkedNodes
                }
            },
            merchantListChange(needToDelete) {
                if (needToDelete && this.operatorType === 'edit') {
                    this.beanInfo.deleteMerchants = needToDelete
                }
            },
            async getDeleteMerchants() {
                if (!this.beanInfo.deleteMerchants || this.beanInfo.deleteMerchants.length === 0) {
                    return []
                }
                const params = {
                    mchntType: '0',
                    selectedOrgInfoList: this.checkedOrgInfo,
                    mchntNo: this.beanInfo.deleteMerchants,
                }
                try {
                    const res = await this.$postJson("/admin/market/commissionManager/getMerchanList", params)
                    if (res.data.type === 'failure') {
                        this.$message.error(res.data.message)
                    } else {
                        const merchantInfo = [];
                        const successData = res.data.data.successData || [];
                        const feeMchntData = res.data.data.feeMchntData || [];
                        const orgMchntData = res.data.data.orgMchntData || [];
                        if (successData.length) {
                            merchantInfo.push(...successData.map(i => {
                                i.oprType = 'D'
                                i.mchntType = '0'
                                return i
                            }))
                        }
                        if (feeMchntData.length) {
                            merchantInfo.push(...feeMchntData.map(i => {
                                i.oprType = 'D'
                                i.mchntType = '0'
                                return i
                            }))
                        }
                        if (orgMchntData.length) {
                            merchantInfo.push(...orgMchntData.map(i => {
                                i.oprType = 'D'
                                i.mchntType = '0'
                                return i
                            }))
                        }
                        return merchantInfo
                    }
                } catch (e) {
                    console.error(e)
                    this.$message.error("获取删除商户信息失败")
                }
            },
            async downloadTemplate() {
                try {
                    await this.$download('admin/market/cashierManager/getExcel?type=0', {}, 'mchntNoBatchImportTemplate.xls')
                } catch (e) {
                    console.error(e)
                }
            },
            async importTemplate() {
                const formData = new FormData()
                const orgInfo = this.checkedOrgInfo
                if (orgInfo.length === 0) {
                    this.$message.error('请选择参与机构')
                    return
                }
                const fileInput = document.createElement('input')
                fileInput.type = 'file'
                fileInput.accept = '.xls,.xlsx'
                fileInput.onchange = async () => {
                    const file = fileInput.files[0]
                    if (!file) {
                        this.$message.error('请选择文件')
                        return
                    }
                    formData.append('excelFile', file)
                    try {
                        const res = await this.$upload('admin/market/cashierManager/upload', formData)
                        if (res.data.code === '100000') {
                            this.$message.success('导入成功')
                            this.$set(this.beanInfo, 'hasUploaded', true)
                            this.$set(this.beanInfo, 'mrctFilePath', res.data.data)
                        } else {
                            this.$message.error(res.data.message)
                        }
                    } catch (e) {
                        console.error(e)
                        this.$message.error('导入失败')
                    }
                }
                fileInput.click()
            },
            templateUploaded(fileUrl) {
                this.$set(this.beanInfo, 'hasUploaded', true)
                this.$set(this.beanInfo, 'mrctFilePath', fileUrl)
            },
            checkAmount(index) {
                const ruleInfo = this.beanInfo.ruleInfo[index]
                if (ruleInfo.criteriaFloor && ruleInfo.criteriaCelling) {
                    if (ruleInfo.criteriaFloor > ruleInfo.criteriaCelling) {
                        this.$message.error('交易金额范围下限不能大于上限')
                    }
                }
            }
        },
        mounted() {
            this.initTreeData();
        }
    }
</script>

<style scoped>
  .child-item {
    background: #F7F8FA;
    border: 1px solid #E0E0E0;
    padding: 20px;
    border-radius: 2px;
    margin: 20px 0;
  }
  .child-item2 {
    width: 672px;
    background: #F7F8FA;
    border: 1px solid #E0E0E0;
    padding: 20px;
    border-radius: 2px;
    margin: 20px 0;
  }

  .tip {
    line-height: 1.4;
  }

  .label {
    margin: 20px 0 10px;
  }

  .step-rule-item {
    display: flex;
    line-height: 1.8;
  }

  .small-input {
    width: 70px;
    margin: 0 5px;
  }

  .small2-input {
    width: 50px;
    margin: 0 5px;
  }

  .small-select {
    width: 100px;
    margin: 0 5px;
  }

  .small-select2 {
    width: 132px;
    margin: 0 5px;
  }

  .hr {
    width: 100%;
    height: 1px;
    background: #E0E0E0;
    margin: 10px 0;
  }

  .form-item {
    width: 50%;
    padding-left: 10px;
    padding-right: 10px;
  }
</style>
